package me.zingon.WebSocket.tools;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by ZTC on 12/26/2016.
 */
@Component
public class VideoTool {

    Map<String, WebSocketSession> sessions = new ConcurrentHashMap<String, WebSocketSession>();

    boolean isSending=false;

    String base64Img;

    public void addWatcher(WebSocketSession session) {
        sessions.put(session.getId(), session);
    }

    public void rmWatcher(WebSocketSession session){
        if(sessions.containsKey(session.getId()))
            sessions.remove(session.getId());
    }

    public void send2All(final String base64Img) {
        Set<Map.Entry<String, WebSocketSession>> set = sessions.entrySet();
        for (Map.Entry<String, WebSocketSession> s : set) {
            try {
                s.getValue().sendMessage(new TextMessage(base64Img));
            }catch (Exception e){
                e.printStackTrace();
                sessions.remove(s.getKey());
            }
        }
//        setBase64Img(base64Img);
//        if(!isSending) {
//            new Thread(new Runnable() {
//                public void run() {
//                    while (true) {
//                        try {
//                            Set<Map.Entry<String, WebSocketSession>> set = sessions.entrySet();
//                            for (Map.Entry<String, WebSocketSession> s : set) {
//                                try {
//                                    if (s.getValue().isOpen())
//                                        s.getValue().sendMessage(new TextMessage(getBase64Img()));
//                                    else
//                                        sessions.remove(s.getKey());
//                                }catch (Exception e){
//                                    e.printStackTrace();
//                                    sessions.remove(s.getKey());
//                                }
//                            }
//                            Thread.sleep(10);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                }
//            }).start();
//            isSending=true;
//        }
    }

    public String getBase64Img() {
        return base64Img;
    }

    public void setBase64Img(String base64Img) {
        this.base64Img = base64Img;
    }
}
